package com.supergzt.context;


import com.supergzt.constant.SecurityConstants;
import com.supergzt.constant.StringConstants;
import com.supergzt.entity.base.LoginUser;
import com.supergzt.utils.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 张钧
 * 获取当前线程变量中的 用户信息
 * 注意： 必须在网关通过请求头的方法传入，同时在HeaderInterceptor拦截器设置值。 否则这里无法获取
 */
public class SecurityContextHolder {
	private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

	public static void set(String key, Object value) {
		Map<String, Object> map = getLocalMap();
		map.put(key, value == null ? StringConstants.NULL : value);
	}

	public static String get(String key) {
		Map<String, Object> map = getLocalMap();
		return map.getOrDefault(key, StringConstants.NULL).toString();
	}

	public static <T> T get(String key, Class<T> clazz) {
		Map<String, Object> map = getLocalMap();
		return clazz.cast(map.getOrDefault(key, null));
	}

	public static Map<String, Object> getLocalMap() {
		Map<String, Object> map = THREAD_LOCAL.get();
		if (map == null) {
			map = new ConcurrentHashMap<>();
			THREAD_LOCAL.set(map);
		}
		return map;
	}

	public static void setLocalMap(Map<String, Object> threadLocalMap) {
		THREAD_LOCAL.set(threadLocalMap);
	}

	public static void remove() {
		THREAD_LOCAL.remove();
	}

	public static void setUserKey(String userKey) {
		set(SecurityConstants.USER_KEY, userKey);
	}

	public static String getUserKey() {
		return get(SecurityConstants.USER_KEY);
	}

	public static void setUserName(String userName) {
		set(SecurityConstants.USERNAME, userName);
	}

	public static String getUserName() {
		String username = get(SecurityConstants.USERNAME);
		return StringUtils.isNull(username) ? SecurityConstants.SYSTEM : username;
	}

	public static void setUserId(Long userId) {
		set(SecurityConstants.USER_ID, userId);
	}

	public static Long getUserId() {
		return Long.valueOf(get(SecurityConstants.USER_ID));
	}

	public static void setLoginUser(LoginUser loginUser) {
		set(SecurityConstants.LOGIN_USER,loginUser);
	}

	public static LoginUser getLoginUser(){
		return get(SecurityConstants.LOGIN_USER, LoginUser.class);
	}
}
